import util from 'common/util.js'
let disp = require("common/broadcast")

var bind = function(that, msg) {
	that.$util.sendRequest(that,"im.chat.bind","POST",0,
	{
		client_id: msg.client_id,
		platform: that.systemInfo.uniPlatform,
		last_timestamp:get_last_timestamp(that)
	}).then(res=>{
		var msgs = res.unread_message;
		for (var key in msgs) {
			saveMsg(that, JSON.parse(msgs[key]), 'accept');
		}
	}).catch(err=>{
		
	});
	
};
var msgAcceptCallBack = function(that){
	that.$util.sendRequest(that,"im.chat.msg.accept.callback","POST",0,null);
};
var initLocalData = function(that) {
	//that.removeStore('historyMsgList');
	var historyMsgList = that.getStore('historyMsgList');
	// console.log("*********************************************************");
	// console.log(historyMsgList);
	// console.log("*********************************************************");
	that['chatModule/setHistoryMsgList'](historyMsgList);
	//console.log(JSON.stringify(that.historyMsgList));
	getUnreadMsgTotal(that);
}
var get_last_timestamp = function(that){
	var lst = that.getStore('last_timestamp');
	if(lst){
		return lst;
	}
	else{
		return 0;
	}
};
var sendMsg = function(that, msg, s_cb, f_cb) {
	that.$util.sendRequest(that,"im.chat.send.msg","POST",0,msg).then(res=>{
		s_cb(res);
	}).catch(err=>{
		f_cb(err);
	});
};
var sendStatus = function(that, msg, status) {
	var historyMsgListCopy = util.deepCopy(that.historyMsgList);
	var myChatLog = historyMsgListCopy[that.userInfo.user_id][that.msgType + msg.to['id']]['chatlog'] || [];
	for (var i = 0; i < myChatLog.length; i++) {
		if (myChatLog[i]['mine'] && myChatLog[i]['timestamp'] == msg.timestamp) {
			if (status) {
				myChatLog[i]['send'] = 2; //发送成功
			} else {
				myChatLog[i]['send'] = 1; //发送失败
			}
		}
	}
	that['chatModule/setHistoryMsgList'](historyMsgListCopy);
	that.setStore('historyMsgList', historyMsgListCopy);
};
var saveMsg = function(that, message, type) {
	if (type == "send") {
		message.read = 1;
	} else {
		if (that.chatWindowsId != message.id) {
			message.read = 0;
		} else {
			message.read = 1;
		}
	}

	var myid = that.userInfo.user_id;
	var historyMsgListCopy = {};
	var local = {};
	if (that.historyMsgList != null && that.historyMsgList != '') {
		if (that.historyMsgList[that.userInfo.user_id] != null && that.historyMsgList[that.userInfo.user_id] != '') {
			if (type == "send") {
				local = that.historyMsgList[that.userInfo.user_id][message.type + message.to['id']] || {};
			} else {
				local = that.historyMsgList[that.userInfo.user_id][message.type + message.id] || {};
			}

		}
	}

	var isNewMsg = 0;
	var chatlog = local.chatlog || [];
	if (chatlog) {
		//有历史消息
		if(chatlog.findIndex(d => d.key === message.key)<0){
		  chatlog.push(message);
		  isNewMsg=1;
		}
		if (chatlog.length > 30) {
			chatlog.shift();
		}
	} else {
		chatlog = [message];
	}


	var history = local.history || {};
	history = [message];



	local.chatlog = chatlog;
	local.history = history;
	historyMsgListCopy = util.deepCopy(that.historyMsgList || {});
	var myHistoryMsg = historyMsgListCopy[that.userInfo.user_id] || {};

	if (type == "send") {
		myHistoryMsg[message.type + message.to['id']] = local;
	} else {
		myHistoryMsg[message.type + message.id] = local;
	}
	historyMsgListCopy[that.userInfo.user_id] = myHistoryMsg;

	that['chatModule/setHistoryMsgList'](historyMsgListCopy);

	that.setStore('historyMsgList', historyMsgListCopy);

	that.setStore('last_timestamp', new Date().getTime());
	// console.log("--------------------设置timestamp--------------------")
	//console.log(JSON.stringify(that.historyMsgList));

	// if(that.chatWindowsId!=message.id && type=="accept"){
	// 	that['chatModule/setUnreadMsgCount'](that.unreadMsgCount+1);
	// }

	getUnreadMsgTotal(that);

	if (type == "accept" && isNewMsg==1) {
		// #ifdef APP-PLUS
		if (plus.os.name == "iOS") {
			plus.ios.invoke(null, "AudioServicesPlaySystemSound", 1007);
		}
		if (plus.os.name == "Android") {
			try {
				var context = plus.android.runtimeMainActivity();
				var RingtoneManager = plus.android.importClass('android.media.RingtoneManager');
				var uri = RingtoneManager.getActualDefaultRingtoneUri(context, RingtoneManager.TYPE_NOTIFICATION);
				var r = RingtoneManager.getRingtone(context, uri);
				plus.android.invoke(r, "play");
			} catch (e) {}
		}
		// #endif
		msgAcceptCallBack(that);
	}

}
var edtMsg = function(that,msg){
	var historyMsgListCopy = util.deepCopy(that.historyMsgList || {});
	var _index = historyMsgListCopy[msg['id']][msg['type']+msg['to']['id']]['chatlog'].findIndex(item => item.key==msg.key );
	historyMsgListCopy[msg['id']][msg['type']+msg['to']['id']]['chatlog'][_index]['content']=msg.content;
	historyMsgListCopy[msg['id']][msg['type']+msg['to']['id']]['chatlog'][_index]['send']=2;
	that['chatModule/setHistoryMsgList'](historyMsgListCopy);
	
}
var getUnreadMsgTotal = function(that) {
	var num = 0;
	var getUnReadCount = function(chatlog) {
		var i = 0;
		for (var n = 0; n < chatlog.length; n++) {
			if (chatlog[n].read == 0) {
				i++;
			}
		}
		return i;
	};
	if (that.historyMsgList != null && that.historyMsgList != '') {
		if (that.historyMsgList[that.userInfo.user_id] != null && that.historyMsgList[that.userInfo.user_id] != '') {
			var local = that.historyMsgList[that.userInfo.user_id] || {};
			for (var key in local) {
				num = num + getUnReadCount(local[key]['chatlog']);
			}
		}
	}
	that['chatModule/setUnreadMsgCount'](num);
	// #ifdef APP-PLUS
	plus.runtime.setBadgeNumber(num);
	// #endif
}
var initFriendList = function(that) {
}
var onMessage = function(that, message) {
	var msg = JSON.parse(message.data);
	switch (msg.message_type) {
		case 'init':
			bind(that, msg);
			return;
		case 'online':
			console.log(msg.id+"上线");
			return;
		case 'chatMessage':
			saveMsg(that, msg.data, 'accept');
			return;
		case 'event':
			if(msg.data){
				disp.fire(msg.do,JSON.parse(msg.data));
			}
			else{
				disp.fire(msg.do);
			}
			return;
	}
}
var localChatTo = function(that,to){
	that['chatModule/setChatTo'](to);
	uni.navigateTo({
		url: "../../pages1/message/chat?friendid=" + to.id + "&unread=0&msgType="+to.type
	});
}
module.exports = {
	bind: bind,
	initLocalData: initLocalData,
	saveMsg: saveMsg,
	sendMsg: sendMsg,
	edtMsg: edtMsg,
	sendStatus: sendStatus,
	onMessage: onMessage,
	localChatTo: localChatTo
}